package com.lzx.iteam;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaRecorder;
import android.os.*;
import android.support.v4.view.ViewPager;
import android.text.*;
import android.util.Log;
import android.view.*;
import android.view.animation.*;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.*;
import com.lzx.iteam.adapter.*;
import com.lzx.iteam.bean.*;
import com.lzx.iteam.bean.aidl.ActiveDetailBean;
import com.lzx.iteam.bean.aidl.EventReplyNewData;
import com.lzx.iteam.emotion.EmotionUtil;
import com.lzx.iteam.widget.gridimg.MyGridView;
import com.lzx.iteam.net.*;
import com.lzx.iteam.provider.CloudDBOperation;
import com.lzx.iteam.provider.EventsMsgDB;
import com.lzx.iteam.selectimage.Bimp;
import com.lzx.iteam.selectimage.Res;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.MyListView;
import com.lzx.iteam.widget.TextViewSpan;
import io.rong.imageloader.core.ImageLoader;
import io.rong.imageloader.core.listener.ImageLoadingListener;
import io.rong.imageloader.core.listener.SimpleImageLoadingListener;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.lzx.iteam.widget.kpswitch.util.KPSwitchConflictUtil;
import com.lzx.iteam.widget.kpswitch.util.KeyboardUtil;
import com.lzx.iteam.widget.kpswitch.widget.KPSwitchPanelLinearLayout;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.res.Configuration;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * Created by shijunting on 15-5-21.
 * 事件详情页面
 */
public class EventDetailContentActivity extends Activity implements View.OnClickListener, View.OnLongClickListener, View.OnTouchListener {

    private String mTitle;
    private String mPublisherId;
    private String mPublisherName;
    private String mPublisherImg;
    private String mPublisherTime;
    private String mReplyCount;
    private String mEventId;
    private String mEventName;
    private String mEventType;//事件类型 0. 全部, 1：公告，2：审批，3：周报，4：普通事件，5：自定义 6:系统通知  7：活动  8：投票 9:签到
    private String mThumeImage;
    private String mOriImage;
    private int mVoteNumber = 1;
    private int mVoteMaxNumber = 1;
    public static String mVote;
    private String mQrCode;
    private String isQrcode;  // 1：有二维码  2：没有二维码
    private ArrayList<String> mOriImages = new ArrayList<String>();
    private AllDialogUtil mDialogUtil;

    private ImageView mIvWeixinShare;
    private ImageView mIvFriendShare;

    private String mEventPart1;
    private String mEventContent1;
    private String mAuthor;
    private PreferenceUtil mPreferenceUtil;
    private String mUid;
    private ArrayList<String> mNameCard = new ArrayList<String>();

    private String mReplyContent;
    private ShareUtil mShareUtil;
    private String mShareContent;

    private List<EventReplyNewData> mReplyDate;
    private ArrayList<EventVoteBean> mVoteReplyDate;
    private EventReplyAdapter mAdapter;
    private Dialog mDialog;
    private ImageLoadingListener animateFirstListener;
    private CloudDBOperation mCloudDBOperation;
    private EventsMsgDB mEventDB;
    private PopupWindow mMoreWindow;
    private boolean isDeleteEvent = false;
    private boolean isTime = true;  // 签到是否显示签到列表  true:显示

    private ImageView mIvEmotion;
    private LinearLayout mEmotionLayout;
    private ViewPager mVpEmotion;
    private LinearLayout mLlEmotionDots;
    private EmotionUtil mEmotionUtil;
    private KPSwitchPanelLinearLayout mChatPanelRoot; //  包裹更多东西的布局
    private LinearLayout mInputLayout; // 底部发送选择输入框

    private ImageView mIvVoice;
    private LinearLayout mVoiceLayout;
    private TextView mTvSoundLength;
    private LinearLayout mLlSoundLengthLayout;
    private TextView mTvSoundNotice;
    private ImageView mIvRecord;

    private float downY;
    private boolean isCanceled = false; // 是否取消录音

    // 语音相关
    private ScaleAnimation mScaleBigAnimation;
    private ScaleAnimation mScaleLittleAnimation;
    private String mSoundData = "";//语音数据
    private String dataPath;
    private boolean isStop;  // 录音是否结束的标志

    private MediaRecorder mRecorder;
    private MediaPlayUtil mMediaPlayUtil;
    private Handler mVoiceHandler;
    private long mStartTime;
    private long mEndTime;
    private int mTime;
    private String mVoiceData;


    private ImageView mIvImg;
    private LinearLayout mImageLayout;
    private TextView mTvPhoto, mTvCamera;
    private LinearLayout mLlSmallImage;

    private String mFilePath;
    private Bitmap mBitMap;
    private List<Map<String, byte[]>> keyByte ;
    private JSONArray imageArray;
    private JSONArray voiceArray;
    private int mImageCount;


    // 公共标题部分
    private TextView mTvEventName;
    private TextView mTvTime;
    private TextView mTvCount;
    private TextView mTvCountNote;
    private LinearLayout mLlCount;
    private ImageView mIvImage;
    private ScrollView mSvOther;
    private EventListData eventData;

    // 主题相关
    private TextView mTvThemeName;
    private TextView mTVThemeHostName;
    private TextView mTvThemTime;
    private TextView mTvReplyCount;
    private TextView mTvPart1;
    private TextView mTvContent1;
    private ImageView mIvSendImage;
    private RelativeLayout mAnnouncementLayput;
    private RelativeLayout mEventImageLayout, mTopLayput;
    private MyGridView mGvEventImage;
    private TextView mTvEventImageCount;
    private MyGridView mActivityImage;
    private MyGridView mAnnouncementImage;

    // 公告部分
    private View mAnLayout;
    private TextView mAnTitle;
    private TextView mAnContent;
    private TextView mAnAuthor;

    // 活动部分
    private View mSvActiveLayout;
    private TextView mTvActiveTitle;
    private TextView mTvActiveTime;
    private TextView mTvActiveAddress;
    private TextView mTvActiveContent;
    private TextView mTvActiteApply;
    private ImageView mIvActiviteImage;
    private MyListView mLvActiveDetail;
    private LinearLayout mLlActiveList;
    private ActiveDetailAdapter mActiveDetailAdapter;
    private ArrayList<ActiveDetailBean> mDetailBeans;
    private long mDeadTime;

    private String mActiveTime;
    private String mActiveAddress;
    private int mHasVoteCount;
    private int mVoteMember;
    private int mApplyCount;
    private String hasJoin;

    // 投票部分
    private View mSvVoteLayout;
    private TextView mTvVoteTitle,mTvVoteNumber;
    private MyListView mLvVoteTop;
    private MyGridView mGvVoteImage;
    private TextView mTvVoteApply;
    private MyListView mLvVoteBottom;
    private ArrayList<String> mVotes;
    private VoteTopAdapter mVoteTopAdapter;
    private VoteDetailAdapter mVoteDetailAdapter;
    public static int index = -1;

    // 签到部分
    private View mSvRegLayout;
    private TextView mTvRegTitle;
    private TextView mTvRegTime;
    private TextView mTvRegAddress;
    private TextView mTvRegNote;
    private TextView mTvRegCode;
    private TextView mTvRegCountDetail;
    private MyListView mLvRegDetail;
    private LinearLayout mLlRegList;
    private LinearLayout mLlRegUnStart;
    private ArrayList<EventRegBean> mJok;
    private ArrayList<EventRegBean> mJokLate;
    private ArrayList<EventRegBean> mRegData;
    private int mJokNone;
    private LinearLayout mLlRegNote;
    private EventRegAdapter mRegAdapter;

    private WebView mWebView;
    private ListView mLvReply;

    private LinearLayout mBack;
    private TextView mTvMember;

    private EditText mEtInput;
    private TextView mTvSend;

    private EventImageAdapter imageAdapter;

    private TextWatcher mTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            mReplyContent = mEtInput.getText().toString().trim();
            if (!StringUtil.isEmpty(mReplyContent)) {
                mTvSend.setVisibility(View.VISIBLE);
                mIvVoice.setVisibility(View.GONE);
            } else {
                if (Bimp.tempSelectBitmap.size() > 0) {
                    mTvSend.setVisibility(View.VISIBLE);
                    mIvVoice.setVisibility(View.GONE);
                } else {
                    mTvSend.setVisibility(View.GONE);
                    mIvVoice.setVisibility(View.VISIBLE);
                }
            }

        }
    };

    public static final int SEND_REPLY = 5001;
    public static final int GET_REPLY = 5002;
    public static final int JOIN_ACTIVE = 5003;
    public static final int VOTE_EVENT = 5004;
    public static final int GET_QN_TOKEN = 5005;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SEND_REPLY:
                    if (msg.arg1 == 0) {
                        //getReply();
                        mReplyContent = "";
                        mEtInput.setText("");

                        EventReplyNewData backData = (EventReplyNewData) msg.obj;
                        mCloudDBOperation.updateEventReply(backData, mEventId);

                        // 判断,如果回复里面还有 Attachments 内容
                        if (!StringUtil.isEmpty(backData.getAttachments())){
                            Constants.NEW_EVENT_REPLY_TIME = backData.getUpdateTime();
                            if (Bimp.mPictureData.size() > 0){
                                Bimp.mPictureData.clear();
                            }
                            for(String data:Bimp.tempSelectBitmap){
                                Bimp.mPictureData.add(data);
                                Log.d("event_new_reply","  path ===   " + data);
                            }
                            Bimp.tempSelectBitmap.clear();
                        }

                        List<EventReplyNewData> replyNewDatas=new ArrayList<EventReplyNewData>();
                        replyNewDatas.add(backData);
                        replyNewDatas.addAll(mReplyDate);
                        mReplyDate.clear();
                        mReplyDate.addAll(replyNewDatas);
                       // mReplyDate.add(backData);
                        mTvReplyCount.setText("共有" + mReplyDate.size() + "条回复");
                        if (mAdapter != null) {
                            //mAdapter.notifyDataSetChanged();
                            mAdapter.bindData(mReplyDate);
                           // mLvReply.setSelection(mReplyDate.size() - 1);
                        } else {
                            mAdapter = new EventReplyAdapter(mReplyDate, EventDetailContentActivity.this);
                            mLvReply.setAdapter(mAdapter);
                        }
                        setImageMsg();

                        // SelectImageAdapter.mSelectedImage.clear();
                        //mIvInputPic.setImageDrawable(getResources().getDrawable(R.drawable.even_image_selector));
                    } else {
                        Toast.makeText(EventDetailContentActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    mDialog.dismiss();
                    break;
                case GET_REPLY:
                    if (msg.arg1 == 0) {
                        if (mEventType.equals("7")) {
                            mReplyDate = (List<EventReplyNewData>) msg.obj;
                            EventReplyNewData replyData = mReplyDate.get(0);
                            mApplyCount = Integer.parseInt(replyData.getJoinCount());
                            mDetailBeans = replyData.getActiveDetailBeans();
                            mActiveDetailAdapter = new ActiveDetailAdapter(EventDetailContentActivity.this, mDetailBeans);
                            mLvActiveDetail.setAdapter(mActiveDetailAdapter);
                            //mTvActiveCount.setText("目前共"+mDetailBeans.size()+"人参与");
                            mTvCount.setText(mDetailBeans.size() + "");
                            if (mDetailBeans.size() > 0) {
                                mLlActiveList.setVisibility(View.VISIBLE);
                            }

                        } else if (mEventType.equals("8")) {
                            mVoteReplyDate = (ArrayList<EventVoteBean>) msg.obj;
                            // 先得到所有投票的人数
                            for (int i = 0; i < mVoteReplyDate.size(); i++) {
                                mHasVoteCount += mVoteReplyDate.get(i).getCount();
                                mVoteReplyDate.get(i).setVote((char) (65 + i) + ": " + mVotes.get(i));
                            }
                            mVoteNumber = msg.arg2;
                            if (mVoteNumber == -1){
                                mVoteNumber = mHasVoteCount;
                            }
                            mTvCount.setText(mVoteNumber + "");
                            mVoteDetailAdapter = new VoteDetailAdapter(EventDetailContentActivity.this, mVoteReplyDate, mHasVoteCount);
                            mLvVoteBottom.setAdapter(mVoteDetailAdapter);

                        } else if (mEventType.equals("9")) {
                            JSONObject result = (JSONObject) msg.obj;
                            JSONObject object = null;
                            try {
                                object = result.getJSONObject("data");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            mJok = new ArrayList<EventRegBean>();
                            mJokLate = new ArrayList<EventRegBean>();
                            mRegData = new ArrayList<EventRegBean>();
                            try {
                                JSONArray jok = object.getJSONArray("jok");
                                for (int i = 0; i < jok.length(); i++) {
                                    EventRegBean bean = new EventRegBean();
                                    bean.setUid(jok.getJSONObject(i).getString("user_id"));
                                    bean.setName(jok.getJSONObject(i).getString("user_name"));
                                    bean.setImage(jok.getJSONObject(i).getString("user_image"));
                                    bean.setRegTime(jok.getJSONObject(i).getString("reg_time"));
                                    bean.setIsTimeOut(false);
                                    mJok.add(bean);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                JSONArray jokLate = object.getJSONArray("jlate");
                                for (int i = 0; i < jokLate.length(); i++) {
                                    EventRegBean bean = new EventRegBean();
                                    bean.setUid(jokLate.getJSONObject(i).getString("user_id"));
                                    bean.setName(jokLate.getJSONObject(i).getString("user_name"));
                                    bean.setImage(jokLate.getJSONObject(i).getString("user_image"));
                                    bean.setRegTime(jokLate.getJSONObject(i).getString("reg_time"));
                                    bean.setIsTimeOut(true);
                                    mJokLate.add(bean);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            try {
                                JSONArray jokNone = object.getJSONArray("jnone");
                                mJokNone = jokNone.length();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            SpannableString jok = new SpannableString(mJok.size() + "");
                            TextViewSpan mJokSize = new TextViewSpan(mJok.size() + "", EventDetailContentActivity.this, -1, 1);
                            jok.setSpan(mJokSize, 0, jok.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

                            SpannableString jokLate = new SpannableString(mJokLate.size() + "");
                            TextViewSpan mJokLateSize = new TextViewSpan(mJokLate.size() + "", EventDetailContentActivity.this, -1, 2);
                            jokLate.setSpan(mJokLateSize, 0, jokLate.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

                            SpannableString jokNone = new SpannableString(mJokNone + "");
                            TextViewSpan mJokNoneSize = new TextViewSpan(mJokNone + "", EventDetailContentActivity.this, -1, 3);
                            jokNone.setSpan(mJokNoneSize, 0, jokNone.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                            mTvRegCountDetail.setText("签到");
                            mTvRegCountDetail.append(jok);
                            mTvRegCountDetail.append("人  迟到");
                            mTvRegCountDetail.append(jokLate);
                            mTvRegCountDetail.append("人  未到");
                            mTvRegCountDetail.append(jokNone);
                            mTvRegCountDetail.append("人");

                            mRegData.addAll(mJok);
                            mRegData.addAll(mJokLate);
                            mTvCount.setText(mRegData.size() + "");
                            mRegAdapter = new EventRegAdapter(EventDetailContentActivity.this, mRegData);
                            mLvRegDetail.setAdapter(mRegAdapter);
                            mLlRegList.setVisibility(View.VISIBLE);

                        } else {
                            mReplyDate = (List<EventReplyNewData>) msg.obj;
                            if (mReplyDate.size() > 0) {
                                mAdapter.bindData(mReplyDate);
                            }
                            mTvReplyCount.setText("共有" + mReplyDate.size() + "条回复");
                        }

                    } else if (msg.arg1 == 7000) {
                        Toast.makeText(EventDetailContentActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        isDeleteEvent = true;
                        mCloudDBOperation.deleteEventByEventId(mEventId);
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(EventDetailContentActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else if (msg.arg1 == 1002 || msg.arg1 == 1003 || msg.arg1 == 1005) {//其他接口也应该加此判断，当前其他接口未加
                            mDialogUtil.titleMsgBtnStyle("提示", (String) msg.obj, getString(R.string.ok));
                            mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

                                @Override
                                public void onConfirmClick(Dialog lDialog) {
                                    lDialog.dismiss();
                                    Intent intent = new Intent(EventDetailContentActivity.this, LoginActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intent);
                                    finish();
                                }

                                @Override
                                public void onCancelClick(Dialog lDialog) {
                                }
                            });
                        } else {
                            Toast.makeText(EventDetailContentActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case JOIN_ACTIVE:
                    mDialog.dismiss();
                    if (msg.arg1 == 0) {
                        if (hasJoin.equals("1")) {
                            hasJoin = "2";
                            mIvActiviteImage.setImageResource(R.drawable.event_unapply_image);
                            mTvActiteApply.setText("您不能参与");
                            mTvActiteApply.setEnabled(false);
                            mApplyCount = mApplyCount - 1;
                            for (int i = 0; i < mDetailBeans.size(); i++) {
                                if (mDetailBeans.get(i).getUid().equals(mUid)) {
                                    mDetailBeans.remove(i);
                                }
                            }
                            mActiveDetailAdapter.notifyDataSetChanged();
                            //mTvActiveCount.setText("目前共"+mDetailBeans.size()+"人参与");
                            mTvCount.setText(mDetailBeans.size() + "");
                            if (mDetailBeans.size() == 0) {
                                mLlActiveList.setVisibility(View.GONE);
                            }
                            //setMyActive();
                            mCloudDBOperation.updateEventApplyCount(mEventId, mApplyCount + "", hasJoin);
                        } else if (hasJoin.equals("0")) {
                            hasJoin = "1";
                            mIvActiviteImage.setImageResource(R.drawable.event_apply_image);
                            mTvActiteApply.setText("退出活动");
                            mApplyCount = mApplyCount + 1;
                            ActiveDetailBean bean = new ActiveDetailBean();
                            bean.setPhone(mNameCard.get(1));
                            bean.setName(mNameCard.get(0));
                            bean.setImage(mNameCard.get(7));
                            bean.setUid(mUid);
                            mDetailBeans.add(bean);
                            mActiveDetailAdapter.notifyDataSetChanged();
                            //mTvActiveCount.setText("目前共"+mDetailBeans.size()+"人参与");
                            mTvCount.setText(mDetailBeans.size() + "");
                            if (mDetailBeans.size() > 0) {
                                mLlActiveList.setVisibility(View.VISIBLE);
                            }
                            //setMyActive();
                            mCloudDBOperation.updateEventApplyCount(mEventId, mApplyCount + "", hasJoin);
                        }

                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(EventDetailContentActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(EventDetailContentActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case VOTE_EVENT:
                    mDialog.dismiss();
                    if (msg.arg1 == 0) {
                        JSONObject result = (JSONObject) msg.obj;
                        try {
                            String vote = result.getJSONObject("data").getString("voted");
                            Log.d("value_vote", "value_vote: "+vote);
                            mVote = vote;
                            mCloudDBOperation.updateEventVote(mEventId, vote);

                            if (mVote.length() > 1){
                                String[] votes = mVote.split(",");
                                for (int i = 0; i < votes.length; i++) {
                                    int k = votes[i].charAt(0) - 65;
                                    int count = mVoteReplyDate.get(k).getCount() + 1;
                                    mVoteReplyDate.get(k).setCount(count);
                                }
                                mHasVoteCount += votes.length;
                            }else{
                                int k = vote.charAt(0) - 65;
                                int count = mVoteReplyDate.get(k).getCount() + 1;
                                mHasVoteCount += 1;
                                mVoteReplyDate.get(k).setCount(count);
                            }
                            mTvCount.setText(mVoteNumber + 1 + "");
                            mVoteDetailAdapter.bindData(mVoteReplyDate, mHasVoteCount);

                            mLvVoteTop.setVisibility(View.GONE);
                            if (mLvVoteBottom.getVisibility() == View.GONE) {
                                mLvVoteBottom.setVisibility(View.VISIBLE);
                            }
                            mLlCount.setVisibility(View.VISIBLE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        index = -1;
                        mVoteTopAdapter.setShowCheck(false);
                        mVoteTopAdapter.notifyDataSetChanged();
                        mTvVoteApply.setEnabled(false);
                        mTvVoteApply.setText("已投票");


                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(EventDetailContentActivity.this, R.string.active_failure_no_network,
                                    Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(EventDetailContentActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case GET_QN_TOKEN:
                    if (msg.arg1 == 0) {
                        Map<String, Object> map = (HashMap<String, Object>) msg.obj;
                        String path = (String) map.get("path");
                        String fileName = (String) map.get("fileName");
                        String voice=(String) map.get("voice");
                        if (!StringUtil.isEmpty(path)) {
                            voiceArray = new JSONArray();
                            try {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("type", "2");
                                jsonObject.put("duration", voice.split("tuandui@lzx")[1]);
                                jsonObject.put("data", fileName);
                                voiceArray.put(jsonObject);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                            setVoice((String) map.get(fileName), path, fileName);
                            sendReply();
                        } else {
                            for (int i = 0; i < keyByte.size(); i++) {
                                Map<String, byte[]> map1 = keyByte.get(i);
                                for (String key : map1.keySet()) {
                                    setPhoto((String) map.get(key), map1.get(key), key);
                                }

                            }

                        }
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("InstanceState", "-- onCreate  ==  ");
        setContentView(R.layout.event_detail_content_layout);
        LocalLogin localLogin = LocalLogin.getInstance();
        if (!localLogin.isLogedin()) {
            localLogin.login(this);
            if (!localLogin.isLogedin()) {
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
                finish();
                return;
            }
        }
/*
        try {
            if (NetServiceManager.getInstance() != null) {
                Log.d("Service", "EventDetailContentActivity---addNewMessageInterface");
                NetServiceManager.getInstance().addNewMessageInterface(newMessageImpl);

            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
*/

        mShareUtil = ShareUtil.getInstance(this);
        mPreferenceUtil = PreferenceUtil.getInstance(this);
        initPropery();
        initView();
        initEmotion();
        getData();
        initSoundData();
        Res.init(this);

        KeyboardUtil.attach(this, mChatPanelRoot,
                // Add keyboard showing state callback, do like this when you want to listen in the
                // keyboard's show/hide change.
                new KeyboardUtil.OnKeyboardShowingListener() {
                    @Override
                    public void onKeyboardShowing(boolean isShowing) {
                        Log.d("ChatActivity", String.format("Keyboard is %s", isShowing ? "showing" : "hiding"));
                    }
                });

        KPSwitchConflictUtil.attach(mChatPanelRoot, mIvImg, mIvEmotion, mIvVoice, mEtInput,
                new KPSwitchConflictUtil.SwitchClickListener() {
                    @Override
                    public void onClickSwitch(boolean switchToPanel, int flag) {

                        if (switchToPanel) {
                            mEtInput.clearFocus();
                            Log.d("switchToPanel", " true ==  " + flag);
                            if (flag == 1) {

                                setIconShow(1);
                                mImageLayout.setVisibility(View.VISIBLE);
                                mEmotionLayout.setVisibility(View.GONE);
                                mVoiceLayout.setVisibility(View.GONE);

                            } else if (flag == 2) {
                                setIconShow(2);
                                mImageLayout.setVisibility(View.GONE);
                                mEmotionLayout.setVisibility(View.VISIBLE);
                                mVoiceLayout.setVisibility(View.GONE);
                            } else {

                                mTvSoundNotice.setVisibility(View.VISIBLE);
                                mIvRecord.setVisibility(View.VISIBLE);
                                mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record));
                                mTvSoundNotice.setText("按住说话");
                                mTvSoundLength.setText("0" + '"');

                                setIconShow(3);
                                mImageLayout.setVisibility(View.GONE);
                                mEmotionLayout.setVisibility(View.GONE);
                                mVoiceLayout.setVisibility(View.VISIBLE);

                            }
                        } else {
                            mEtInput.requestFocus();
                            setIconShow(0);
                            Log.d("switchToPanel", " false ==  " + flag);
                        }
                    }
                });

    }

    /**
     * 设置图标
     *
     * @param flag
     */
    private void setIconShow(int flag) {
        if (flag == 1) {
            mIvImg.setImageDrawable(getResources().getDrawable(R.drawable.selector_keyboard_btn));
            mIvEmotion.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
            mIvVoice.setImageDrawable(getResources().getDrawable(R.drawable.selector_voice_icon));
        } else if (flag == 2) {
            mIvImg.setImageDrawable(getResources().getDrawable(R.drawable.selector_image_icon));
            mIvEmotion.setImageDrawable(getResources().getDrawable(R.drawable.selector_keyboard_btn));
            mIvVoice.setImageDrawable(getResources().getDrawable(R.drawable.selector_voice_icon));
        } else if (flag == 3) {
            mIvImg.setImageDrawable(getResources().getDrawable(R.drawable.selector_image_icon));
            mIvEmotion.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
            mIvVoice.setImageDrawable(getResources().getDrawable(R.drawable.selector_keyboard_btn));
        } else {
            mIvImg.setImageDrawable(getResources().getDrawable(R.drawable.selector_image_icon));
            mIvEmotion.setImageDrawable(getResources().getDrawable(R.drawable.selector_emotion_icon));
            mIvVoice.setImageDrawable(getResources().getDrawable(R.drawable.selector_voice_icon));
        }
    }

    /**
     * 初始化表情
     */
    private void initEmotion() {
        mEmotionUtil = new EmotionUtil(this, mEtInput, mLlEmotionDots, mVpEmotion);
        mEmotionUtil.initStaticFaces();
        mEmotionUtil.initViewPager();
        mVpEmotion.setOnPageChangeListener(mEmotionUtil.new PageChange());
    }

    @Override
    protected void onResume() {
        super.onResume();
        // TODO 把未读消息改为已读
        mEventDB.updateAllMsgReaded(mEventId);
        mCloudDBOperation.updateEventUnReadCount(mEventId, "0");
        if (eventData.getHasRead().equals("0")) {
            mCloudDBOperation.updateEventNotNew(mEventId);
        }
        setImageMsg();

        if ("6".equals(mEventType)){
            setWebView(eventData.getUrl1());
        }
    }

    public void initPropery() {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        mReplyDate = new ArrayList<EventReplyNewData>();
        mVoteReplyDate = new ArrayList<EventVoteBean>();
        mDialog = AllDialogUtil.getInstance(this).waitDialog();
        animateFirstListener = new AnimateFirstDisplayListener();
        mCloudDBOperation = new CloudDBOperation(this);
        mEventDB = new EventsMsgDB(this);
        mDialogUtil = AllDialogUtil.getInstance(this);
        mUid = mPreferenceUtil.getString(PreferenceUtil.CLIENT_USEID, "－1");
        mNameCard = (ArrayList<String>) mPreferenceUtil.getCloudContact(Constants.CONTACT_NAME_CARD);
    }

    public void initSoundData() {

        dataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Yun/Sounds/";
        File folder = new File(dataPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        mMediaPlayUtil = MediaPlayUtil.getInstance();
//        mRecorder = new MediaRecorder();
    }


    public void setReply(EventReplyNewData reply) {
        if (reply.getEventId().equals(mEventId)) {
            mEventDB.updateAllMsgReaded(mEventId);
            mCloudDBOperation.updateEventUnReadCount(mEventId, "0");
            reply.setIsReaded(true);
            mReplyDate.add(reply);
            if (mAdapter != null) {
                mAdapter.bindData(mReplyDate);
            } else {
                mAdapter = new EventReplyAdapter(mReplyDate, EventDetailContentActivity.this);
                mLvReply.setAdapter(mAdapter);
            }
            mTvReplyCount.setText("共有" + mReplyDate.size() + "条回复");
        }
    }


    private class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {

        final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    //FadeInBitmapDisplayer.animate(imageView, 500);
                    displayedImages.add(imageUri);
                }
            }
        }
    }

    private void initView() {
        mTvEventName = (TextView) findViewById(R.id.event_tv_name);
        mTvTime = (TextView) findViewById(R.id.event_tv_time);
        mTvCount = (TextView) findViewById(R.id.event_tv_count);
        mTvCountNote = (TextView) findViewById(R.id.event_tv_count_note);
        mLlCount = (LinearLayout) findViewById(R.id.head_ll_count);
        mIvImage = (ImageView) findViewById(R.id.event_iv_head);
        mSvOther = (ScrollView) findViewById(R.id.event_sv_other);
        mChatPanelRoot = (KPSwitchPanelLinearLayout) findViewById(R.id.chat_panel_root);
        mInputLayout = (LinearLayout) findViewById(R.id.event_input_layout);

        mIvEmotion = (ImageView) findViewById(R.id.iv_list_emotion);
        mIvImg = (ImageView) findViewById(R.id.iv_list_img);
        mEmotionLayout = (LinearLayout) findViewById(R.id.ll_emotion_layout);
        mImageLayout = (LinearLayout) findViewById(R.id.rl_chat_more);
        mVoiceLayout = (LinearLayout) findViewById(R.id.chat_ll_sound);
        mVpEmotion = (ViewPager) findViewById(R.id.emotion_viewpager);
        mLlEmotionDots = (LinearLayout) findViewById(R.id.emotion_dots_container);

        mIvVoice = (ImageView) findViewById(R.id.iv_list_voice);
        mTvSoundLength = (TextView) findViewById(R.id.chat_tv_sound_length);
        mLlSoundLengthLayout = (LinearLayout) findViewById(R.id.chat_tv_sound_length_layout);
        mTvSoundNotice = (TextView) findViewById(R.id.chat_tv_sound_notice);
        mIvRecord = (ImageView) findViewById(R.id.chat_record);

        mTvPhoto = (TextView) findViewById(R.id.tv_chat_image);
        mTvCamera = (TextView) findViewById(R.id.tv_chat_camera);

        mLlSmallImage = (LinearLayout) findViewById(R.id.ll_small_image_layout);

        mTvPhoto.setOnClickListener(this);
        mTvCamera.setOnClickListener(this);
        mIvRecord.setOnTouchListener(new VoiceTouch());

        mBack = (LinearLayout) findViewById(R.id.ll_back);
        mBack.setOnClickListener(this);
        mTvMember = (TextView) findViewById(R.id.tv_title_right);
        mTvMember.setOnClickListener(this);
        mEtInput = (EditText) findViewById(R.id.even_et_input);
        mEtInput.setOnTouchListener(this);
        mEtInput.addTextChangedListener(mTextWatcher);
        mTvSend = (TextView) findViewById(R.id.even_tv_input_send);
        mTvSend.setOnClickListener(this);
        mLvReply = (ListView) findViewById(R.id.even_lv_reply);
        mLvReply.setOnTouchListener(this);

        mTopLayput = (RelativeLayout) findViewById(R.id.rl_head);

        mWebView = (WebView) findViewById(R.id.event_detail_web_view);
        // 设置webView支持js
        /*WebSettings ws = mWebView.getSettings();
        ws.setJavaScriptEnabled(true);
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {

                if (newProgress == 100) {
                    mDialog.dismiss();
                }
                super.onProgressChanged(view, newProgress);
            }
        });*/
        mAnnouncementLayput = (RelativeLayout) findViewById(R.id.announcement_rl_layout);
        mAnLayout = findViewById(R.id.layout_announcement);
        mAnTitle = (TextView) findViewById(R.id.announcement_tv_title);
        mAnContent = (TextView) findViewById(R.id.announcement_tv_content);
        mAnAuthor = (TextView) findViewById(R.id.announcement_tv_author);

        mAnnouncementImage = (MyGridView) findViewById(R.id.announcement_gv_image);
        mAnnouncementImage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(EventDetailContentActivity.this, ImagePagerActivity.class);
                intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_URL_ARRAY);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, mOriImages);
                intent.putExtra(ImagePagerActivity.EXTRA_THUME_IMAGES, mThumeImage);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, i);
                startActivity(intent);

            }
        });


        // 活动部分
        mSvActiveLayout = findViewById(R.id.layout_active);
        mTvActiveTitle = (TextView) findViewById(R.id.event_active_tv_title);
        mTvActiveTime = (TextView) findViewById(R.id.event_active_tv_time);
        mTvActiveAddress = (TextView) findViewById(R.id.event_active_tv_address);
        mTvActiveContent = (TextView) findViewById(R.id.event_active_tv_content);
        mTvActiteApply = (TextView) findViewById(R.id.event_active_tv_apply);
        mIvActiviteImage = (ImageView) findViewById(R.id.event_active_iv_image);
        mLlActiveList = (LinearLayout) findViewById(R.id.active_ll_list);
        mTvActiteApply.setOnClickListener(this);
        mActivityImage = (MyGridView) findViewById(R.id.event_active_gv_image);
        mActivityImage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(EventDetailContentActivity.this, ImagePagerActivity.class);
                intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_URL_ARRAY);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, mOriImages);
                intent.putExtra(ImagePagerActivity.EXTRA_THUME_IMAGES, mThumeImage);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, i);
                startActivity(intent);

            }
        });

        // 投票部分
        mSvVoteLayout = findViewById(R.id.layout_vote);
        mTvVoteTitle = (TextView) findViewById(R.id.event_vote_tv_title);
        mLvVoteTop = (MyListView) findViewById(R.id.event_vote_lv_top);
        mGvVoteImage = (MyGridView) findViewById(R.id.event_vote_gv_image);
        mTvVoteApply = (TextView) findViewById(R.id.event_vote_tv_apply);
        mLvVoteBottom = (MyListView) findViewById(R.id.event_vote_lv_bottom);
        mLvActiveDetail = (MyListView) findViewById(R.id.active_lv_detail);
        mTvVoteNumber = (TextView) findViewById(R.id.event_vote_tv_vote_number);
        mGvVoteImage.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(EventDetailContentActivity.this, ImagePagerActivity.class);
                intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_URL_ARRAY);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, mOriImages);
                intent.putExtra(ImagePagerActivity.EXTRA_THUME_IMAGES, mThumeImage);
                intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, i);
                startActivity(intent);

            }
        });
        mLvVoteTop.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                /*if (EventDetailContentActivity.index == i) {
                    EventDetailContentActivity.index = -1;
                } else {
                    EventDetailContentActivity.index = i;
                }
                mVoteTopAdapter.notifyDataSetChanged();*/

                /*VoteTopAdapter.ViewHolder holder = (VoteTopAdapter.ViewHolder) view.getTag();
                holder.mCheck.toggle();// 在每次获取点击的item时改变checkbox的状态*/
                if (mVoteMaxNumber == 1){
                    mVoteTopAdapter.isSelected.clear();
                    mVoteTopAdapter.isSelected.add(i);
                }else{
                    boolean flag = true;
                    for (int j = 0;j<mVoteTopAdapter.isSelected.size();j++){
                        if (i == mVoteTopAdapter.isSelected.get(j)){
                            mVoteTopAdapter.isSelected.remove(j);
                            flag = false;
                            break;
                        }
                    }
                    if (flag){
                        if (mVoteTopAdapter.isSelected.size() == mVoteMaxNumber){
                            Toast.makeText(EventDetailContentActivity.this, "最多选择"+mVoteMaxNumber+"项", Toast.LENGTH_SHORT).show();
                        }else{
                            mVoteTopAdapter.isSelected.add(i);
                        }
                    }
                }
                mVoteTopAdapter.notifyDataSetChanged();
            }
        });

        // 签到部分
        mSvRegLayout = findViewById(R.id.layout_reg);
        mTvRegTitle = (TextView) findViewById(R.id.event_reg_tv_title);
        mTvRegTime = (TextView) findViewById(R.id.event_reg_tv_time);
        mTvRegAddress = (TextView) findViewById(R.id.event_reg_tv_address);
        mTvRegNote = (TextView) findViewById(R.id.event_reg_tv_note);
        mTvRegCode = (TextView) findViewById(R.id.event_reg_tv_code);
        mTvRegCountDetail = (TextView) findViewById(R.id.event_reg_tv_detail);
        mLvRegDetail = (MyListView) findViewById(R.id.event_reg_lv_reg);
        mLlRegNote = (LinearLayout) findViewById(R.id.event_reg_ll_note);
        mLlRegList = (LinearLayout) findViewById(R.id.event_reg_ll_list_detatil);
        mLlRegUnStart = (LinearLayout) findViewById(R.id.event_reg_ll_unstart);
        mTvRegCode.setOnClickListener(this);


    }

    /**
     * 生成一个随机的文件名
     *
     * @return
     */
    public String getRandomFileName() {
        String rel = "";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());
        rel = formatter.format(curDate);
        rel = rel + new Random().nextInt(1000);
        return rel;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        switch (view.getId()) {
            case R.id.even_lv_reply:
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    setIconShow(0);
                    KPSwitchConflictUtil.hidePanelAndKeyboard(mChatPanelRoot);
                }
                break;
            case R.id.even_et_input:
                if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    setIconShow(0);
                    KPSwitchConflictUtil.mFlag = 0;
                }
                break;

        }
        return false;

    }

    /**
     * 录音的触摸监听
     */
    class VoiceTouch implements View.OnTouchListener {

        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {

            switch (motionEvent.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    downY = motionEvent.getY();
                    mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record_pressed));
                    mTvSoundNotice.setText("向上滑动取消发送");
                    mSoundData = dataPath + getRandomFileName() + ".amr";

                    // 防止开权限后崩溃
                    if (mRecorder != null) {
                        Log.i("recoder", " !=  null");
                        //mRecorder.release();
                        mRecorder.reset();
                    } else {
                        mRecorder = new MediaRecorder();
                        Log.i("recoder", " == null ");
                    }
                    mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
                    mRecorder.setOutputFile(mSoundData);
                    mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
                    try {
                        mRecorder.prepare();
                    } catch (IOException e) {
                        Log.i("recoder", "prepare() failed-Exception-" + e.toString());
                    }
                    try {
                        mRecorder.start();
                        mStartTime = System.currentTimeMillis();
                        mLlSoundLengthLayout.setVisibility(View.VISIBLE);
                        mTvSoundLength.setText("0" + '"');
                        // 开启定时器
                        mHandler.postDelayed(runnable, 1000);
                    } catch (Exception e) {
                        Log.i("recoder", "prepare() failed-Exception-" + e.toString());
                    }
                    initScaleAnim();
                    mScaleBigAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            if (mScaleLittleAnimation != null) {
                                mIvRecord.startAnimation(mScaleLittleAnimation);
                            }
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    mScaleLittleAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            if (mScaleBigAnimation != null) {
                                mIvRecord.startAnimation(mScaleBigAnimation);
                            }
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {

                        }
                    });
                    mIvRecord.startAnimation(mScaleBigAnimation);

                    break;
                case MotionEvent.ACTION_UP:
                    if (!isStop) {
                        mEndTime = System.currentTimeMillis();
                        mTime = (int) ((mEndTime - mStartTime) / 1000);
                        stopRecord();
                        //stopPlay();

                        mTvSoundLength.setText("0" + '"');
                        mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record));
                        mTvSoundNotice.setText("按住说话");

                        try {
                            mVoiceData = StringUtil.encodeBase64File(mSoundData);
                            mVoiceData = mVoiceData + "tuandui@lzx" + mTime;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                       /* if ("0".equals(mIsActive)) {
                            Toast.makeText(EventDetailContentActivity.this, "对不起，该小组已解散,无法发送消息", Toast.LENGTH_LONG).show();
                        } else {*/
                        if (isCanceled) {
                            deleteSoundFileUnSend();
                        } else {
                            //发送语音获取token
                            if (mVoiceData != null) {
                                getQnToken(mSoundData, mVoiceData);

                            }
                            //隐藏下面语音图片键盘等布局
                            setIconShow(0);
                            KPSwitchConflictUtil.hidePanelAndKeyboard(mChatPanelRoot);
                        }
                        // }
                    }
                    break;
                case MotionEvent.ACTION_CANCEL: // 开权限录音取消
                    Log.i("record_test", "权限影响录音录音");
                    mHandler.removeCallbacks(runnable);
                    mLlSoundLengthLayout.setVisibility(View.GONE);
                    if (mRecorder != null) {
                        mRecorder.release();
                        mRecorder = null;
                        System.gc();
                    }
                    mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record));
                    mIvRecord.clearAnimation();
                    mTvSoundNotice.setText("按住说话");
                    isCanceled = true;
                    mScaleBigAnimation = null;
                    mScaleLittleAnimation = null;

                    break;

                case MotionEvent.ACTION_MOVE: // 滑动手指
                    Log.i("record_test", " ACTION_MOVE  权限影响录音录音");
                    float moveY = motionEvent.getY();
                    if (downY - moveY > 100) {
                        isCanceled = true;
                        mTvSoundNotice.setText("松开手指可取消录音");
                        mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record));
                    }
                    if (downY - moveY < 20) {
                        isCanceled = false;
                        mIvRecord.setImageDrawable(getResources().getDrawable(R.drawable.record_pressed));
                        mTvSoundNotice.setText("向上滑动取消发送");
                    }
                    break;

            }
            return true;
        }
    }


    /**
     * 初始化录音动画
     */
    public void initScaleAnim() {

        // TODO 放大
        mScaleBigAnimation = new ScaleAnimation(1.0f, 1.3f, 1.0f, 1.3f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mScaleBigAnimation.setDuration(700);

        // TODO 缩小
        mScaleLittleAnimation = new ScaleAnimation(1.3f, 1.0f, 1.3f, 1.0f,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mScaleLittleAnimation.setDuration(700);

    }


    /**
     * 录音完毕后，若不发送，则删除文件
     */
    public void deleteSoundFileUnSend() {
        mTime = 0;
        if (!"".equals(mSoundData)) {
            try {
                File file = new File(mSoundData);
                file.delete();
                mSoundData = "";
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 结束录音
     */
    public void stopRecord() {
        mIvRecord.clearAnimation();
        mScaleBigAnimation = null;
        mScaleLittleAnimation = null;
        if (mTime < 1) {
            deleteSoundFileUnSend();
            isCanceled = true;
            Toast.makeText(EventDetailContentActivity.this, "录音时间太短，长按开始录音", Toast.LENGTH_SHORT).show();
        } else {
            // 不加  "" 空串 会出  Resources$NotFoundException 错误
            mTvSoundLength.setText(mTime + "" + '"');
            Log.i("record_test", "录音成功");

        }
        mRecorder.setOnErrorListener(null);
        try {
            mRecorder.stop();
            mRecorder.reset();
            mRecorder.release();
        } catch (Exception e) {
            Log.i("recoder", "stop() failed");
            isCanceled = true;
            mIvRecord.setVisibility(View.VISIBLE);
            mTvSoundLength.setText("");
            Toast.makeText(EventDetailContentActivity.this, "录音发生错误,请重新录音", Toast.LENGTH_LONG).show();
            Log.i("record_test", "录音发生错误");
        }
        mHandler.removeCallbacks(runnable);
        if (mRecorder != null) {
            mRecorder = null;
            System.gc();
        }

    }


    // 定时器
    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            // handler自带方法实现定时器
            try {
                long endTime = System.currentTimeMillis();
                int time = (int) ((endTime - mStartTime) / 1000);
                //mRlSoundLengthLayout.setVisibility(View.VISIBLE);
                mTvSoundLength.setText(time + "" + '"');
                // 限制录音时间不长于两分钟
                if (time > 119) {
                    isStop = true;
                    mTime = time;
                    stopRecord();
                    Toast.makeText(EventDetailContentActivity.this, "时间过长", Toast.LENGTH_SHORT).show();
                } else {
                    mHandler.postDelayed(this, 1000);
                    isStop = false;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };


    /**
     * 弹出复制的pop
     *
     * @param v
     * @param context
     */
    public void showCopyPop(final View v, final String context) {
        //解析菜单view
        final View layoutMenu = LayoutInflater.from(this).inflate(R.layout.event_copy_layout, null);
        final PopupWindow window = new PopupWindow(layoutMenu, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        //让弹出框获取焦点（为了让菜单里面的按钮可以点击）
        window.setFocusable(true);
        //触摸弹出框外面位置，自动dismiss
        window.setBackgroundDrawable(new ColorDrawable());//这句很关键！
        window.setOutsideTouchable(true);
        //显示PopupWindow
        /** 这个很重要 ,获取弹窗的长宽度 */
        layoutMenu.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = layoutMenu.getMeasuredWidth();
        int popupHeight = layoutMenu.getMeasuredHeight();
        /** 获取父控件的位置 */
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        /** 显示位置 */
        if (location[1] - popupHeight > 100) {
            layoutMenu.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.bottom_corner_bg));
            window.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, location[1]
                    - popupHeight);
        } else {
            layoutMenu.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.top_corner_bg));
            //window.showAsDropDown(v,0,0,Gravity.NO_GRAVITY);
            window.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, location[1]
                    + v.getHeight());
        }
        v.setBackgroundResource(R.color.event_content_copy);
        window.update();

        //设置menu里面按钮点击监听
        TextView button1 = (TextView) layoutMenu.findViewById(R.id.event_tv_copy);//复制
        layoutMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // clip.getText(); // 粘贴
                clip.setText(context); // 复制
                v.setBackgroundResource(R.color.white);
                Toast.makeText(EventDetailContentActivity.this, "已复制到粘贴板", Toast.LENGTH_SHORT).show();
                window.dismiss();
            }
        });
        window.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                v.setBackgroundResource(R.color.white);
            }
        });

    }


    /**
     * @param i i = 1 公告字数很多 popupwindow 显示在屏幕中间
     *          i = 0 公告字不多  popupwindow 显示在内容的下面
     */
    public void showClickPop(int i) {
        View mainView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.event_long_click_layout, null);
        TextView copy = (TextView) mainView.findViewById(R.id.event_content_copy);
        final TextView share = (TextView) mainView.findViewById(R.id.event_content_share);


        copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClipboardManager clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // clip.getText(); // 粘贴
                clip.setText(mEventContent1); // 复制
                mTvContent1.setBackgroundResource(R.color.white);
                Toast.makeText(EventDetailContentActivity.this, "已复制到粘贴板", Toast.LENGTH_SHORT).show();
                mMoreWindow.dismiss();
            }
        });

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mShareUtil.shareToWx(null, mEventContent1, null, 1, null);
                mTvContent1.setBackgroundResource(R.color.white);
                mMoreWindow.dismiss();
            }
        });

        mMoreWindow = new PopupWindow(getApplicationContext());
        mMoreWindow.setBackgroundDrawable(new BitmapDrawable());
        mMoreWindow.setFocusable(true);
        mMoreWindow.setTouchable(true);
        mMoreWindow.setContentView(mainView);
        mMoreWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        mMoreWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        if (i == 0) {
            mMoreWindow.showAsDropDown(mTvContent1, Gravity.CENTER_HORIZONTAL, 0);
        } else {
            mMoreWindow.showAtLocation(mAnnouncementLayput, Gravity.CENTER, 0, 0);
        }
        mMoreWindow.update();
        AlphaAnimation aa = new AlphaAnimation(0.5f, 1.0f);
        aa.setDuration(300);
        ScaleAnimation sa = new ScaleAnimation(0.5f, 1.0f, 0.5f,
                1.0f, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        sa.setDuration(300);
        AnimationSet set = new AnimationSet(false);
        set.addAnimation(aa);
        set.addAnimation(sa);
        mainView.startAnimation(set);

        mMoreWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mTvContent1.setBackgroundResource(R.color.white);
            }
        });
    }


    public void getData() {
        Intent intent = getIntent();
        eventData = (EventListData) intent.getSerializableExtra("event_msg");
        mEventId = eventData.getEventId();
        mEventType = eventData.getEventType();
        mLvReply.addHeaderView(getHeadView(), null, false);
        setData(eventData);
        mIvSendImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("0".equals(eventData.getUserId()) || StringUtil.isEmpty(eventData.getUserId())) {
                    Toast.makeText(EventDetailContentActivity.this, "对不起，该用户未注册", Toast.LENGTH_LONG).show();
                } else {
                    Intent intent = new Intent(EventDetailContentActivity.this, ContactNameCardActivity.class);
                    intent.putExtra("user_id", eventData.getUserId());
                    startActivity(intent);
                }
            }
        });
        mIvImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("0".equals(eventData.getUserId()) || StringUtil.isEmpty(eventData.getUserId())) {
                    Toast.makeText(EventDetailContentActivity.this, "对不起，该用户未注册", Toast.LENGTH_LONG).show();
                } else {
                    Intent intent = new Intent(EventDetailContentActivity.this, ContactNameCardActivity.class);
                    intent.putExtra("user_id", eventData.getUserId());
                    startActivity(intent);
                }
            }
        });

        Log.d("event_data", eventData.toString());

        mIvWeixinShare = (ImageView) findViewById(R.id.iv_share_weixin);
        mIvFriendShare = (ImageView) findViewById(R.id.iv_share_friend);
        if (mEventType.equals("7")) {
            getReply();
            mShareContent = mEventContent1;
        } else if (mEventType.equals("8")) {
            getReply();
            mShareContent = "投票结果";
        } else if (mEventType.equals("9")) {
            mShareContent = DateUtil.getDetailDate(mDeadTime) + "\n" + mActiveAddress;
        } else {
            getDataReply();
            mShareContent = mEventContent1;
        }
        mIvWeixinShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mShareUtil.shareToWx(mTitle, mShareContent, "http://ituandui.cn/mobile?event_id=" + mEventId, 3, null);
            }
        });
        mIvFriendShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mShareUtil.shareToWxCircle(mShareContent, "http://ituandui.cn/mobile?event_id=" + mEventId, null);
            }
        });

    }

    public View getHeadView() {
        View view = LayoutInflater.from(this).inflate(R.layout.event_head_layout, null);
        mTvThemeName = (TextView) view.findViewById(R.id.even_tv_theme);
        mTVThemeHostName = (TextView) view.findViewById(R.id.even_tv_tmeme_host);
        mTvThemTime = (TextView) view.findViewById(R.id.even_tv_tmeme_time);
        mTvReplyCount = (TextView) view.findViewById(R.id.event_detail_tv_reply);
        mTvPart1 = (TextView) view.findViewById(R.id.event_detail_tv_part1);
        mTvContent1 = (TextView) view.findViewById(R.id.event_detail_tv_content1);
        mIvSendImage = (ImageView) view.findViewById(R.id.event_iv_send);
        mEventImageLayout = (RelativeLayout) view.findViewById(R.id.rl_event_image_layout);
        mGvEventImage = (MyGridView) view.findViewById(R.id.event_gv_image);
        mTvEventImageCount = (TextView) view.findViewById(R.id.even_tv_image_count);
        return view;
    }

    public void setData(EventListData event) {

        mEventName = event.getEventName();
        mTitle = event.getEventTitle();
        mPublisherId = event.getUserId();
        mPublisherImg = event.getEventAvatar();
        mPublisherName = event.getUserName();
        mPublisherTime = event.getCreateTime();
        mReplyCount = event.getReplyCount();
        mEventPart1 = event.getInitTitle1();
        mEventContent1 = event.getContent1();
        mAuthor = event.getAuthor();
        mThumeImage = event.getThumbImage();
        mOriImage = event.getOriImage();
        mVote = event.getVotes();
        if (!StringUtil.isEmpty(event.getVoteMaxNumber())) {
            mVoteMaxNumber = Integer.parseInt(event.getVoteMaxNumber());
        }
        isQrcode = event.getIsQrcode();
        mQrCode = event.getQrcode();
        String[] images = null;
        if (!StringUtil.isEmpty(mThumeImage)) {
            images = mThumeImage.split(",");
        }

        String[] oriImage = null;
        if (!StringUtil.isEmpty(mOriImage)) {
            oriImage = mOriImage.split(",");
            for (int i = 0; i < oriImage.length; i++) {
                mOriImages.add(oriImage[i]);
            }
        }

        if (!StringUtil.isEmpty(mPublisherName)) {
            mTvEventName.setText(mPublisherName);
        }
        if (!StringUtil.isEmpty(mPublisherTime)) {
            long date = Long.parseLong(mPublisherTime);
            mTvTime.setText(DateUtil.getDetailDate(date * 1000));
        }
        if (!StringUtil.isEmpty(mPublisherImg)) {
            ImageLoaderInterface.imageLoader.displayImage(mPublisherImg, mIvImage, ImageLoaderInterface.optionHeadImage);
        }

        if (mEventType.equals("1")) {
            mAnLayout.setVisibility(View.VISIBLE);
            if (!StringUtil.isEmpty(mTitle)) {
                mAnTitle.setText(mTitle);
            }

            if (!StringUtil.isEmpty(mEventContent1)) {
                mAnContent.setText("      " + mEventContent1);
            }

            if (!StringUtil.isEmpty(mAuthor)) {
                mAnAuthor.setVisibility(View.VISIBLE);
                mAnAuthor.setText(mAuthor);
            } else {
                mAnAuthor.setVisibility(View.GONE);
            }

            if (images != null && images.length > 0) {
                mAnnouncementImage.setVisibility(View.VISIBLE);
                imageAdapter = new EventImageAdapter(this, "", images);
                mAnnouncementImage.setAdapter(imageAdapter);
            } else {
                mAnnouncementImage.setVisibility(View.GONE);
            }


        } else if (mEventType.equals("7")) {
            mSvActiveLayout.setVisibility(View.VISIBLE);
            mSvOther.smoothScrollBy(0, 20);

            mActiveTime = event.getActivityTime();
            mActiveAddress = event.getActivitySite();
            if (event.getJoinCount() == null) {
                mApplyCount = 0;
            } else {
                mApplyCount = Integer.parseInt(event.getJoinCount());
            }
            hasJoin = event.getHasJoin();

            if (!StringUtil.isEmpty(mTitle)) {
                mTvActiveTitle.setText(mTitle);
            }
            if (!StringUtil.isEmpty(mActiveTime)) {
                mDeadTime = Long.parseLong(mActiveTime);
                if (mActiveTime.length() == 10) {
                    mDeadTime = mDeadTime * 1000;
                }
                mTvActiveTime.setText(DateUtil.getDetailDate(mDeadTime));


            }
            if (!StringUtil.isEmpty(mActiveAddress)) {
                mTvActiveAddress.setText(mActiveAddress);
            }
            if (!StringUtil.isEmpty(mEventContent1)) {
                mTvActiveContent.setText(mEventContent1);
            }
            long curTime = System.currentTimeMillis();

            if (hasJoin != null) {
                if (hasJoin.equals("1")) {
                    mIvActiviteImage.setImageResource(R.drawable.event_apply_image);
                    mTvActiteApply.setText("取消报名");
                    mLlCount.setVisibility(View.VISIBLE);
                } else if (hasJoin.equals("2")) {
                    mIvActiviteImage.setImageResource(R.drawable.event_unapply_image);
                    mTvActiteApply.setText("您不能参与");
                    mTvActiteApply.setEnabled(false);
                    mLlCount.setVisibility(View.VISIBLE);
                } else {
                    mIvActiviteImage.setImageResource(R.drawable.event_unapply_image);
                    mTvActiteApply.setText("我要报名");
                }

            } else {
                hasJoin = "0";
                mIvActiviteImage.setImageResource(R.drawable.event_unapply_image);
                mTvActiteApply.setText("我要报名");
            }
            if (curTime > mDeadTime) {
                mTvActiteApply.setText("活动已结束");
                mTvActiteApply.setEnabled(false);
            }

            if (images != null && images.length > 0) {
                mActivityImage.setVisibility(View.VISIBLE);
                imageAdapter = new EventImageAdapter(this, "", images);
                mActivityImage.setAdapter(imageAdapter);
            } else {
                mActivityImage.setVisibility(View.GONE);
            }

        } else if (mEventType.equals("8")) {

            mSvVoteLayout.setVisibility(View.VISIBLE);
            mSvActiveLayout.setVisibility(View.GONE);
            mTvVoteTitle.setText(mTitle);
            mTvVoteNumber.setText("最多选" + mVoteMaxNumber + "项");
            mTvCountNote.setText("投票人数");
            mTvVoteApply.setOnClickListener(this);
            mVotes = new ArrayList<String>();
            String[] votes = mEventContent1.split(",");
            for (int i = 0; i < votes.length; i++) {
                mVotes.add(votes[i]);
            }
            if (StringUtil.isEmpty(mVote)) {
                mTvVoteApply.setText("我要投票");
                mVoteTopAdapter = new VoteTopAdapter(this, mVotes, true);
                mVoteTopAdapter.isSelected.clear();
                mLvVoteTop.setVisibility(View.VISIBLE);
                mLlCount.setVisibility(View.GONE);
            } else {
                mTvVoteApply.setText("已投票");
                mTvVoteApply.setEnabled(false);
                mLvVoteBottom.setVisibility(View.VISIBLE);
                mLlCount.setVisibility(View.VISIBLE);
            }
            mLvVoteTop.setAdapter(mVoteTopAdapter);

            if (images != null && images.length > 0) {
                mGvVoteImage.setVisibility(View.VISIBLE);
                imageAdapter = new EventImageAdapter(this, "", images);
                mGvVoteImage.setAdapter(imageAdapter);
            } else {
                mGvVoteImage.setVisibility(View.GONE);
            }

        } else if (mEventType.equals("9")) {
            mSvRegLayout.setVisibility(View.VISIBLE);
            mTvRegTitle.setText(mTitle);
            mTvCountNote.setText("签到人数");
            mActiveTime = event.getActivityTime();
            mActiveAddress = event.getActivitySite();
            if (!StringUtil.isEmpty(mActiveTime)) {
                mDeadTime = Long.parseLong(mActiveTime);
                if (mActiveTime.length() == 10) {
                    mDeadTime = mDeadTime * 1000;
                }
                mTvRegTime.setText(DateUtil.getDetailDate(mDeadTime));
            }
            if (!StringUtil.isEmpty(mActiveAddress)) {
                mTvRegAddress.setText(mActiveAddress);
            }
            if (!StringUtil.isEmpty(mEventContent1)) {
                mTvRegNote.setText(mEventContent1);
                mLlRegNote.setVisibility(View.VISIBLE);
            }
            if (!StringUtil.isEmpty(event.getIsQrcode()) && event.getIsQrcode().equals("1")) {
                if (event.getUserType().equals("1")) {
                    mTvRegCode.setVisibility(View.VISIBLE);
                }

                if (mUid.equals(event.getUserId())) {
                    mTvRegCode.setVisibility(View.VISIBLE);
                }
                long time = System.currentTimeMillis();
                if (time > mDeadTime - 60 * 60 * 1000) {
                    mLlCount.setVisibility(View.VISIBLE);
                    isTime = true;
                } else {
                    mLlRegUnStart.setVisibility(View.VISIBLE);
                    isTime = false;
                }
            } else {
                isTime = false;
            }
            getReply();


        } else {

            if (StringUtil.isEmpty(mTitle)) {
                mTvThemeName.setText("发给您一份" + mEventName);
            } else {
                mTvThemeName.setText(mTitle);
            }
            mTVThemeHostName.setText(mPublisherName);
            if (mPublisherTime != null) {
                mTvThemTime.setText(DateUtil.getDetailDate(Long.parseLong(mPublisherTime) * 1000));
            }
            mTvReplyCount.setText("共有" + mReplyCount + "条回复");


            if (!StringUtil.isEmpty(mEventPart1)) {
                mTvPart1.setVisibility(View.VISIBLE);
                mTvPart1.setText(mEventPart1);
            }

            if (!StringUtil.isEmpty(mEventContent1)) {
                mTvContent1.setVisibility(View.VISIBLE);
                mTvContent1.setText(mEventContent1);
            }
            mTvContent1.setOnLongClickListener(this);
            mTvThemeName.setOnLongClickListener(this);

            ImageLoaderInterface.imageLoader.displayImage(event.getEventAvatar(), mIvSendImage, ImageLoaderInterface.optionHeadImage, animateFirstListener);
            if (images != null && images.length > 0) {
                mEventImageLayout.setVisibility(View.VISIBLE);
                mGvEventImage.setVisibility(View.VISIBLE);
                imageAdapter = new EventImageAdapter(this, images, mOriImages, mThumeImage, "");
                mGvEventImage.setAdapter(imageAdapter);
                mTvEventImageCount.setText("共" + images.length + "张图片");
            } else {
                mEventImageLayout.setVisibility(View.GONE);
                mGvEventImage.setVisibility(View.GONE);
            }

            if ("6".equals(mEventType)) {
                mDialog.show();
                mSvOther.setVisibility(View.GONE);
                mWebView.setVisibility(View.VISIBLE);
                mTvMember.setVisibility(View.GONE);
                setWebView(event.getUrl1());

            } else {
                mSvOther.setVisibility(View.GONE);
                mWebView.setVisibility(View.GONE);
                mTvMember.setVisibility(View.VISIBLE);
                mLvReply.setVisibility(View.VISIBLE);
                mInputLayout.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setWebView(String url){
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setAllowFileAccess(true);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.loadUrl(url);
        mWebView.setWebChromeClient(new WebChromeClient() {

            @Override
            public void onProgressChanged(WebView view, int newProgress) {

                if (newProgress == 100) {
                    mDialog.dismiss();
                }
                super.onProgressChanged(view, newProgress);
            }
        });
    }

    /**
     * 获取普通事件回复、活动结果、投票结果、会议签到结果
     */
    public void getReply() {
        MyMessage.GetReplyMessage message = null;
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ID, mEventId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_TYPE, mEventType));
        if ("8".equals(mEventType)) {
            message = new MyMessage.GetReplyMessage(mHandler.obtainMessage(GET_REPLY), mEventDB, mEventId, mEventType, mVotes.size());
        } else {
            if ("9".equals(mEventType) && !isTime) {
                message = new MyMessage.GetReplyMessage(null, mEventDB, mEventId, mEventType);
            } else {
                message = new MyMessage.GetReplyMessage(mHandler.obtainMessage(GET_REPLY), mEventDB, mEventId, mEventType);
            }
        }
        message.mApi = AsynHttpClient.API_EVENT_GET_COMMENT;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);

    }

    /**
     * 参与或者退出活动
     */
    public void toApplyActivite(String type) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ID, mEventId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_TYPE, type));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(JOIN_ACTIVE));
        message.mApi = AsynHttpClient.API_EVENT_JOIN;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
    }

    /**
     * 进行投票
     */
    public void toVote(String vote) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ID, mEventId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_VOTE_OPTION, vote));
        GetMsgHttpReceiver message = new GetMsgHttpReceiver(mHandler.obtainMessage(VOTE_EVENT));
        message.mApi = AsynHttpClient.API_EVENT_VOTE;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
    }

    /**
     * 从数据库中获取评论
     */
    public void getDataReply() {
        new AsyncTask<String, Void, List<EventReplyNewData>>() {

            @Override
            protected List<EventReplyNewData> doInBackground(String... strings) {

                return mEventDB.findEventReplyByEventId(mEventId, 10, 1);
            }

            @Override
            protected void onPostExecute(List<EventReplyNewData> eventReplyNewDatas) {
                super.onPostExecute(eventReplyNewDatas);
                if (mAdapter == null) {
                    mAdapter = new EventReplyAdapter(eventReplyNewDatas, EventDetailContentActivity.this);
                    mLvReply.setAdapter(mAdapter);
                } else {
                   /* mLvReply.setAdapter(mAdapter);
                    mAdapter.notifyDataSetChanged();*/
                }
                mTvReplyCount.setText("共有" + eventReplyNewDatas.size() + "条回复");
                getReply();
            }
        }.execute();
    }

    /**
     * 发表回复
     */
    public void sendReply() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ID, mEventId));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_INIT_CONTENT, mReplyContent));
        if (voiceArray != null && voiceArray.length() > 0) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ATTACHMENT, voiceArray.toString()));
        } else if (imageArray != null && imageArray.length() > 0) {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ATTACHMENT, imageArray.toString()));
        } else {
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ATTACHMENT, ""));
        }

        MyMessage.SendReplyMessage message = new MyMessage.SendReplyMessage(mHandler.obtainMessage(SEND_REPLY), EventDetailContentActivity.this);
        message.mApi = AsynHttpClient.API_EVENT_ADD_COMMENT;
        message.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(message);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                Bimp.deleteAllPhoto();
                finish();
                break;
            case R.id.tv_title_right:
                if (isDeleteEvent) {
                    Toast.makeText(EventDetailContentActivity.this, "对不起，该事件已被删除", Toast.LENGTH_LONG).show();
                } else {
                    Intent member = new Intent(EventDetailContentActivity.this, EventReceiveMemberActivity.class);
                    member.putExtra("event_id", mEventId);
                    if ("0".equals(isQrcode)) {
                        member.putExtra("event_type", "9.5");
                    } else {
                        member.putExtra("event_type", mEventType);
                    }
                    startActivity(member);
                }
                break;
            case R.id.even_tv_input_send:
                if (isDeleteEvent) {
                    Toast.makeText(EventDetailContentActivity.this, "对不起，该事件已被删除", Toast.LENGTH_LONG).show();
                } else {
                    if (StringUtil.isEmpty(mReplyContent) && Bimp.tempSelectBitmap.size() == 0) {
                        Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
                    } else {
                        imageArray = new JSONArray();
                        voiceArray = new JSONArray();
                        keyByte= new ArrayList<Map<String, byte[]>>();
                        if (Bimp.tempSelectBitmap.size() > 0) {
                            StringBuilder stringBuilder = new StringBuilder();
                            for (String image : Bimp.tempSelectBitmap) {
                                Map<String, byte[]> token = new HashMap<String, byte[]>();
                                String key = UUID.randomUUID().toString() + System.currentTimeMillis();
                                if (mBitMap != null) {
                                    if (!mBitMap.isRecycled()) {
                                        mBitMap.recycle();
                                    }
                                    mBitMap = null;
                                }
                                mBitMap = PhotoUtil.readBitmapFromPath(EventDetailContentActivity.this, image, true);
                                if (mBitMap != null && !mBitMap.isRecycled()) {
                                    byte[] bytes = PhotoUtil.compressImage(mBitMap);
                                    token.put(key, bytes);
                                }
                                stringBuilder.append(key + ",");
                                keyByte.add(token);
                                try {
                                    JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("type", "1");
                                    jsonObject.put("data", key);
                                    imageArray.put(jsonObject);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            getQnToken(stringBuilder.substring(0, stringBuilder.length() - 1));
                        }
                        sendReply();
                        //隐藏下面语音图片键盘等布局
                        setIconShow(0);
                        KPSwitchConflictUtil.hidePanelAndKeyboard(mChatPanelRoot);
                        mDialog.show();
                    }
                }
                break;
            case R.id.event_active_tv_apply:
                if (hasJoin.equals("1")) {
                    showWarningDialog();
                } else {
                    toApplyActivite("1");
                    mDialog.show();
                }
                break;
            case R.id.event_vote_tv_apply:
                String voteMsg = "";
                if (mVoteMaxNumber == 1){
                    if (mVoteTopAdapter.isSelected.size() == 0){
                        Toast.makeText(EventDetailContentActivity.this, "请选择", Toast.LENGTH_SHORT).show();
                        return;
                    }else{
                        voteMsg = (char) (mVoteTopAdapter.isSelected.get(0) + 65) + "";
                    }
                }else{
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0;i<mVoteTopAdapter.isSelected.size();i++){
                        sb.append((char) (mVoteTopAdapter.isSelected.get(i) + 65) + ",");
                    }
                    if (!StringUtil.isEmpty(sb.toString())){
                        voteMsg = sb.toString().substring(0,sb.toString().length() -1);
                    }
                }

                if (StringUtil.isEmpty(voteMsg)) {
                    Toast.makeText(EventDetailContentActivity.this, "请选择", Toast.LENGTH_SHORT).show();
                } else {
                    toVote(voteMsg);
                    mDialog.show();
                }
                break;
            case R.id.event_reg_tv_code:
                Intent intent = new Intent(EventDetailContentActivity.this, RegCodeActivity.class);
                intent.putExtra("code_image", mQrCode);
                startActivity(intent);
                break;
            case R.id.tv_chat_image:
                Intent intent2 = new Intent(this, ImageFileActivity.class);
                intent2.putExtra("image_number", 3);
                startActivity(intent2);
                break;
            case R.id.tv_chat_camera:
                mFilePath = PhotoUtil.doTakePhotoEvent(this);
                break;
        }
    }

    @Override
    public boolean onLongClick(View view) {
        switch (view.getId()) {
            case R.id.event_detail_tv_content1:
                showCopyPop(view, mEventContent1);
                break;
            case R.id.even_tv_theme:
                showCopyPop(view, mTitle);
                break;
        }
        return false;
    }

    /**
     * 退出活动后，如果再想参与，提示消息
     */
    private void showWarningDialog() {
        mDialogUtil.titleMsgBtnClick("", getResources().getString(R.string.active_waring), "确定", "取消");
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {

            @Override
            public void onConfirmClick(Dialog lDialog) {
                toApplyActivite("0");
                mDialog.show();
                lDialog.dismiss();

            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (mChatPanelRoot.getVisibility() == View.VISIBLE) {

                    setIconShow(0);
                    KPSwitchConflictUtil.hidePanelAndKeyboard(mChatPanelRoot);
                    return true;
                }
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                }
                Bimp.deleteAllPhoto();
                finish();
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 页面返回后，停止系统通知音频播放
        if (mWebView != null) {
            mWebView.loadUrl("about:blank");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
/*
        try {
            if (NetServiceManager.getInstance() != null) {
                Log.d("Service", "EventDetailContentActivity---removeNewMessageInterface");
                NetServiceManager.getInstance().removeNewMessageInterface(newMessageImpl);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
*/
        stopPlay();

    }

    public void stopPlay() {
        if (mMediaPlayUtil.isPlaying()) {
            mMediaPlayUtil.stop();
        }

    }


    /**
     * @param newConfig 处理横竖屏切换，activity 被杀死，网页音频重新播放的问题
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 检测屏幕的方向：纵向或横向
        if (this.getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_LANDSCAPE) {
            //当前为横屏， 在此处添加额外的处理代码
            mTopLayput.setVisibility(View.GONE);
            Log.d("InstanceState", "--onConfigurationChanged  ==  横屏 " );

        } else if (this.getResources().getConfiguration().orientation
                == Configuration.ORIENTATION_PORTRAIT) {
            //当前为竖屏， 在此处添加额外的处理代码
            mTopLayput.setVisibility(View.VISIBLE);

            Log.d("InstanceState", "--onConfigurationChanged  ==  竖屏 ");

            if ("4".equals(mEventType) && Bimp.tempSelectBitmap.size() > 0){
                KPSwitchConflictUtil.mFlag = 1;
                KPSwitchConflictUtil.showPanel(mChatPanelRoot);
                setIconShow(1);
            }

        }
    }

    /**
     * 判断ListView是否到底部
     *
     * @param listView
     * @return
     */
    public boolean isListViewReachBottomEdge(final ListView listView) {
        boolean result = false;
        if (listView.getLastVisiblePosition() == (listView.getCount() - 2)) {
            final View bottomChildView = listView.getChildAt(listView.getLastVisiblePosition() - listView.getFirstVisiblePosition());
            result = (listView.getHeight() >= bottomChildView.getBottom());
        }
        return result;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
           /*  case Constants.SELECT_IMG_BACK:
                if (resultCode == RESULT_OK) {
                    setImageMsg();
                } else if (resultCode == 100) {
                    String imgPath = data.getStringExtra(Constants.IMAGE_PATH);
                    Bimp.tempSelectBitmap.add(imgPath);
                    setImageMsg();
                }
                break;
           case TAKE_PHOTO:
                if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {
                    Bitmap bm = (Bitmap) data.getExtras().get("data");
                    String tempPath = PhotoUtil.saveBitmaptoSdCard(bm, "/Yun/Images/");
                    tempPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Yun/Images/" + tempPath;
                    Bimp.tempSelectBitmap.add(tempPath);
                }
                break;*/
            case PhotoUtil.CAMERA_WITH_DATAA:
                if (Bimp.tempSelectBitmap.size() < 3 && resultCode == RESULT_OK) {
                    Bitmap bitmap = PhotoUtil.readBitmapFromPath(this, mFilePath, false);
                    int degree = PhotoUtil.getExifOrientation(mFilePath);
                    if (degree != 0) {
                        bitmap = PhotoUtil.rotaingImageView(bitmap, degree);
                        FileUtils.deleteFolderFile(mFilePath, true);
                        mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Yun/Images/" + PhotoUtil.saveBitmaptoSdCard(bitmap, "/Yun/Images");
                    }
                    Bimp.tempSelectBitmap.add(mFilePath);
                    setImageMsg();
                }
                break;
        }
    }

    //改成动态添加布局的，不能用这种方式，删除会有问题
    private void setImageMsg() {
        int imgSize = 0;
        if (Bimp.tempSelectBitmap != null) {
            imgSize = Bimp.tempSelectBitmap.size();
            if (imgSize > 0) {
                mLlSmallImage.setVisibility(View.VISIBLE);
                mTvSend.setVisibility(View.VISIBLE);
                mIvVoice.setVisibility(View.GONE);

                mLlSmallImage.removeAllViews();
                for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
                    final String image = Bimp.tempSelectBitmap.get(i);
                    final int position = i;
                    final View view = LayoutInflater.from(EventDetailContentActivity.this).inflate(R.layout.small_image_layout, mLlSmallImage, false);
                    RelativeLayout mLayout = (RelativeLayout) view.findViewById(R.id.rl_small_image);
                    ImageView mIvDelete = (ImageView) view.findViewById(R.id.iv_small_image_delete);
                    ImageView mIvImage = (ImageView) view.findViewById(R.id.iv_small_image);
                    ImageLoader.getInstance().displayImage("file://" + image, mIvImage, ImageLoaderInterface.optionEventImage);

                    mLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            Bimp.tempSelectBitmap.remove(position);
                            Bimp.deletePhoto(image);
                            Bimp.tempSelectBitmap.remove(image);
                            mLlSmallImage.removeView(view);
//                            mImageHLinearLayout.removeViewAt(position);
                            if (Bimp.tempSelectBitmap.size() <= 0) {
                                showImageLayout(false);
                            } else {
                                showImageLayout(true);
                            }
                        }
                    });
/*
                    mIvImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(EventDetailContentActivity.this, ImagePagerActivity.class);
                            intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_LOCAL_ARRAY);
                            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, Bimp.tempSelectBitmap);
                            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                            startActivity(intent);
                        }
                    });
*/
                    mLlSmallImage.addView(view);
                }

            } else {
                mLlSmallImage.setVisibility(View.GONE);
                if (!StringUtil.isEmpty(mReplyContent)) {
                    mTvSend.setVisibility(View.VISIBLE);
                    mIvVoice.setVisibility(View.GONE);
                } else {
                    mTvSend.setVisibility(View.GONE);
                    mIvVoice.setVisibility(View.VISIBLE);
                }

            }

        }


    }

    public void showImageLayout(boolean flag) {
        if (flag) {
            mLlSmallImage.setVisibility(View.VISIBLE);
        } else {
            mLlSmallImage.setVisibility(View.GONE);
            if (!StringUtil.isEmpty(mReplyContent)) {
                mTvSend.setVisibility(View.VISIBLE);
                mIvVoice.setVisibility(View.GONE);
            } else {
                mTvSend.setVisibility(View.GONE);
                mIvVoice.setVisibility(View.VISIBLE);
            }

        }
    }


    public void getQnToken(String path,String voiceData) {
        String fileName = UUID.randomUUID().toString() + System.currentTimeMillis();
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_KEY, fileName));
        GetQnTokenMsg getQnTokenMsg = new GetQnTokenMsg(mHandler.obtainMessage(GET_QN_TOKEN));
        getQnTokenMsg.setParams(path, fileName,voiceData);
        getQnTokenMsg.mApi = AsynHttpClient.API_QN_GET_EVENT_TOKEN;
        getQnTokenMsg.mParams = mList;
        AsynHttpClient.getInstance(this).execUserHttp(getQnTokenMsg);
    }


    public void getQnToken(String keys) {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_KEY, keys));
        GetQnTokenMsg getQnTokenMsg = new GetQnTokenMsg(mHandler.obtainMessage(GET_QN_TOKEN));
        getQnTokenMsg.mApi = AsynHttpClient.API_QN_GET_EVENT_TOKEN;
        getQnTokenMsg.mParams = mList;
        AsynHttpClient.getInstance(this).execUserHttp(getQnTokenMsg);
    }


    //设置图片
    public void setPhoto(String token, byte[] file, String fileName) {
        Log.d("七牛--token", token);
        Log.d("七牛--fileName", fileName);
        DialerApp.getUploadManager(this).put(file, fileName, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject response) {
                        Log.d("七牛--info.isOk()", info.isOK() + "--response" + response);
                        ++mImageCount;
                        if (imageArray.length() == mImageCount) {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Bimp.deleteAllPhotoAfterSend();
                                    Constants.NEW_EVENT_REPLY_TIME = "";
                                    Log.d("event_new_reply","  reply_time  ==  clear");
                                }
                            }, 3000);

                        }
                    }
                }, null);
    }


    public void setVoice(String token, String path, String fileName) {
        if (token != null)
            Log.d("七牛--token", token);
        if (fileName != null)
            Log.d("七牛--fileName", fileName);
        DialerApp.getUploadManager(this).put(path, fileName, token,
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo info, JSONObject response) {
                        Log.d("七牛--info.isOk()", info.isOK() + "--response" + response);

                    }
                }, null);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        outState.putString("pic_path", mFilePath);

        Log.d("InstanceState", "--onSaveInstanceState  ==  " + KPSwitchConflictUtil.mFlag);


        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        mFilePath = savedInstanceState.getString("pic_path");
        Log.d("InstanceState", "--onRestoreInstanceState  ==  " + KPSwitchConflictUtil.mFlag);
        KPSwitchConflictUtil.showPanel(mChatPanelRoot);
        setIconShow(1);
        super.onRestoreInstanceState(savedInstanceState);
    }
}
